<?php
namespace app\common\controller;
use think\Db;
use Process\RedisClient;
use Sms\Sms;
use Exception;
class SmsWork extends \app\common\controller\Base
{
    /**
     * @var
     */
    public $redis_client ;

    /**
     * @var
     */
    public $sms_api_arr;

    /**
     * @var
     */
    public $current_sms_api_use;

    /**
     * @var
     */
    public $api_list;

    /**
     * redis 配置
     * @var
     */
    public $redis_conf ;

    /**
     * @var string
     */
    protected $default_api_use ='ChuangLan' ;

    /**
     * @var string
     */
    protected $yx_key = 'yingxiao';

    /**
     * @var string
     */
    protected $hy_key = 'hangye';

    /**
     * 每次循环执行任务数
     * @var int
     */
    protected $exec_num = 50 ;

    /**
     * 配置更新默认间隔
     * @var int
     */
    protected $setting_expire = 86400 ;

    /**
     * 上次配置更新时间
     * @var
     */
    protected $last_expire_time ;

    protected $model;

    /**
     * 余额不足提醒服务
     * @var
     */
    public $notice_msg ;

    /**
     * SmsWork constructor.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * redis队列进程
     */
    public function queueWork()
    {
        try{
            $api_obj_arr = $this->baseInit(__METHOD__, __LINE__);
            if(!$api_obj_arr)
            {
                return ;
            }
            if(empty($this->model['mobile_hangye_list']))
            {
                $this->model['mobile_hangye_list'] = Db::name('mobile_hangye_list') ;
            }
            if(empty($this->model['mobile_yingxiao_list']))
            {
                $this->model['mobile_yingxiao_list'] = Db::name('mobile_yingxiao_list') ;
            }
            //格式化获取模板
            $template = $this->redis_client->hGetAll(MOBILE_TEMPLATE);
            if(!$template)
            {
                throw new Exception('【短信发送队列】获取短信模板失败, '.$this->redis_client->getlasterror());
            }
            foreach($template as $k=>$v)
            {
                $template[$k] = json_decode($v,true);
            }
            //业务处理逻辑
            $i=0;
            do
            {
                $json = '';
                try{
                    $json =$this->redis_client->Pop(MOBILE_QUEUE);
                    if($json)
                    {
                        $json_data = json_decode($json,true) ;
                        if($json_data)
                        {
                            if($template[$json_data['template']]['var_content'])
                            {
                                $json_data['content'] = preg_replace($template[$json_data['template']]['var_content'],$json_data['var_content'],$template[$json_data['template']]['content']);
                            }
                            else
                            {
                                $json_data['content'] = $template[$json_data['template']]['content'] ;
                            }
                            $res = $this->send($api_obj_arr, $json_data);
                            $to_arr = explode(',', $json_data['to']);
                            foreach($to_arr as $v)
                            {
                                $this->redis_client->Push("mobile_{$json_data['channel']}_list",json_encode([
                                    'status'         => $res['status'],
                                    'status_info'    => $res['status_info'],
                                    'send_time'      => $res['send_time'],
                                    'msg_id'         => (string)$res['msgid'],
                                    'to'             => $v,
                                    'by_account'     => $res['by_account'],
                                    'template_id'    => $json_data['template'],
                                    'var_content'    => $json_data['var_content']?json_encode($json_data['var_content']):'',
                                    'request_client' => $json_data['request_client'],
                                    'sign'           => $json_data['sign'],
                                    'appoint_api'    => $json_data['appoint_api'],
                                    'api_time'       =>$json_data['api_time'],
                                    'add_time'       => $json_data['add_time'],
                                ],JSON_UNESCAPED_UNICODE));
                            }
                        }
                        $this->redis_client->dealer(MOBILE_QUEUE,$json);
                    }
                }
                catch (Exception $e)
                {
                    $error_string = sprintf("error:%s,code:%s,method：%s,line:%d,file stat:%s,trace:%s,",$e->getMessage(),$e->getCode(),__METHOD__,$e->getLine(),$e->getFile(),$e->getTraceAsString());
                    $this->fileLog($error_string);
                }
                $i++ ;
            }while($json && $i< $this->exec_num);
        }
        catch (Exception $e)
        {
            $error_string = sprintf("error:%s,code:%s,method：%s,line:%d,file stat:%s,trace:%s,",$e->getMessage(),$e->getCode(),__METHOD__,$e->getLine(),$e->getFile(),$e->getTraceAsString());
            $this->fileLog($error_string);
            return ;
        }
    }

    /**
     * 入库行业
     */
    public function dbSaveHy()
    {
        try{
            if(!$this->redis_client)
            {
                $this->redis_client = new RedisClient($this->redis_conf);
            }
            if(empty($this->model['mobile_hangye_list']))
            {
                $this->model['mobile_hangye_list'] = Db::name('mobile_hangye_list') ;
            }

            // 每次入五百
            $num = 500;
            // 行业
            $res = $this->redis_client->lRange('mobile_hangye_list',-$num,-1);
            if($res)
            {
                foreach ($res as $k=>$v)
                {
                    $res[$k] = json_decode($v,true);
                    $res[$k]['insert_time'] = time();
                }
                if($this->model['mobile_hangye_list']->insertAll($res))
                {
                    if(!$this->redis_client->ltrim('mobile_hangye_list',0,-($num+1))) $this->fileLog("【删除已经入库的redis数据】失败!".sprintf("method：%s,line:%d,file stat:%s",__METHOD__,__LINE__,__FILE__)) ;;
                }
            }
        } catch (Exception $e)
        {
            $error_string = sprintf("error:%s,code:%s,method：%s,line:%d,file stat:%s,trace:%s,",$e->getMessage(),$e->getCode(),__METHOD__,$e->getLine(),$e->getFile(),$e->getTraceAsString());
            $this->fileLog($error_string);
            return ;
        }
    }

    /**
     * 入库营销
     */
    public function dbSaveYx()
    {
        try{
            if(!$this->redis_client)
            {
                $this->redis_client = new RedisClient($this->redis_conf);
            }

            if(empty($this->model['mobile_yingxiao_list']))
            {
                $this->model['mobile_yingxiao_list'] = Db::name('mobile_yingxiao_list') ;
            }
            // 每次入五百
            $num = 500;
            // 营销
            $res = $this->redis_client->lRange('mobile_yingxiao_list',-$num,-1);
            if($res)
            {
                foreach ($res as $k=>$v)
                {
                    $res[$k] = json_decode($v,true);
                    $res[$k]['insert_time'] = time();
                }
                if($this->model['mobile_yingxiao_list']->insertAll($res))
                {
                    if(!$this->redis_client->ltrim('mobile_yingxiao_list',0,-($num+1))) $this->fileLog("【删除已经入库的redis数据】失败!".sprintf("method：%s,line:%d,file stat:%s",__METHOD__,__LINE__,__FILE__)) ;;
                }
            }
        } catch (Exception $e)
        {
            $error_string = sprintf("error:%s,code:%s,method：%s,line:%d,file stat:%s,trace:%s,",$e->getMessage(),$e->getCode(),__METHOD__,$e->getLine(),$e->getFile(),$e->getTraceAsString());
            $this->fileLog($error_string);
            return ;
        }
    }

    /**
     * 配置更新
     */
    public function confReady()
    {
        try{
            if(!$this->redis_client) $this->redis_client = new RedisClient($this->redis_conf);
            // 初始化数据路连
            if (empty($this->model['setting'])) $this->model['setting'] = Db::name('setting');
            if (empty($this->model['mobile_hangye_list'])) $this->model['mobile_hangye_list'] = Db::name('mobile_hangye_list');
            if (empty($this->model['mobile_yingxiao_list'])) $this->model['mobile_yingxiao_list'] = Db::name('mobile_yingxiao_list');
            if (empty($this->model['mobile_template'])) $this->model['mobile_template'] = Db::name('mobile_template');
            if (empty($this->model['email_template'])) $this->model['email_template'] = Db::name('email_template');
            // 配置更新策略
            if(empty($this->last_expire_time)|| time() > $this->last_expire_time+$this->setting_expire)
            {
                // 配置更新频率设定
                $setting = $this->model['setting']->where("`key` = '".UPDATE_TIMES."' AND `status` = 1")->field('setting')->find();
                $this->setting_expire = (int)json_decode($setting['setting'],true)['config_update_times']*60; // 单位为分钟
                // 提醒设置
                $notice_setting = $this->model['setting']->where('`key`= "'.MOBILE_ACCOUNT_NOT_ENOUGH_NOTICE.'" and `status` = 1')->field('type,setting')->find();
                if($this->redis_client->hset($notice_setting['type'],MOBILE_ACCOUNT_NOT_ENOUGH_NOTICE,$notice_setting['setting'])===false ) $this->fileLog("更新【短信账号余额不足提醒设置】失败!".sprintf("method：%s,line:%d,file stat:%s",__METHOD__,__LINE__,__FILE__));
                //默认签名配置更新
                $setting = $this->model['setting']->where('`type` = "'.SIGN_CONF_TYPE.'" and status = 1')->field('setting')->find();
                if($this->redis_client->set(MOBILE_DEFAULT_SIGN_CACHE, $setting['setting'])===false  ) $this->fileLog("更新【默认签名配置】失败!".sprintf("method：%s,line:%d,file stat:%s",__METHOD__,__LINE__,__FILE__));
                //邮件账号设置更新
                $setting = $this->model['setting']->where('type = "'.EMAIL_CONF_TYPE.'"  and status = 1')->field('`key`,setting')->select();
                $setting_tmp = [] ;
                foreach($setting as $k=>$v)
                {
                    $setting_tmp[$v['key']] = $v['setting'] ;
                }
                $this->redis_client->del(EMAIL_CONF_TYPE);
                if($this->redis_client->hMset(EMAIL_CONF_TYPE, $setting_tmp)===false) $this->fileLog("更新【邮件账号配置】失败!".sprintf("method：%s,line:%d,file stat:%s",__METHOD__,__LINE__,__FILE__)) ;
                //是否需要更新fpm缓存
                $need_reload = 1 ;
                //邮件模板
                $setting = $this->model['email_template']->where("is_del = 0")->field('id,title,var_title,content,var_content')->select();
                $setting_tmp = [] ;
                foreach($setting as $k=>$v)
                {
                    $v['var_title'] = json_decode($v['var_title'],true) ;
                    $v['var_content'] = json_decode($v['var_content'],true) ;
                    //处理成正则数据
                    if(!empty($v['var_title']))
                    {
                        foreach ($v['var_title'] as $m=>$n)
                        {
                            $v['var_title'][$m] = "/$n/i" ;
                        }
                    }
                    else
                    {
                        $v['var_title'] = '';
                    }
                    if(!empty($v['var_content']))
                    {
                        foreach ($v['var_content'] as $m=>$n)
                        {
                            $v['var_content'][$m] = "/$n/i" ;
                        }
                    }
                    else
                    {
                        $v['var_content'] = '';
                    }
                    $setting_tmp[$v['id']] = json_encode($v,JSON_UNESCAPED_UNICODE);
                }
                if($this->redis_client->hMset(EMAIL_TEMPLATE, $setting_tmp)===false) $this->fileLog("更新【邮件模板配置】失败!".sprintf("method：%s,line:%d,file stat:%s",__METHOD__,__LINE__,__FILE__)) ;
                //短信模板
                $setting = $this->model['mobile_template']->where("is_del = 0")->field('id,content,var_content')->select();
                $setting_tmp = [] ;
                foreach($setting as $k=>$v)
                {
                    $v['var_content'] = json_decode($v['var_content'],true) ;
                    if(!empty($v['var_content']))
                    {
                        foreach ($v['var_content'] as $m=>$n)
                        {
                            $v['var_content'][$m] = "/$n/i" ;
                        }
                    }
                    else{
                        $v['var_content'] = '';
                    }
                    $setting_tmp[$v['id']] = json_encode($v,JSON_UNESCAPED_UNICODE);
                }
                if($this->redis_client->hMset(MOBILE_TEMPLATE, $setting_tmp)===false) $this->fileLog("更新【短信模板配置】失败!".sprintf("method：%s,line:%d,file stat:%s",__METHOD__,__LINE__,__FILE__)) ;
                unset($setting_tmp,$setting,$k,$v,$m,$n);
            }
            //短信api 和账号设置
            $res = $this->model['setting']->where('type = "'.MOBILE_CONF_TYPE.'"')->field('`key`,setting,status')->select();
            if($res)
            {
                $api_setting_cache = [] ;
                foreach($res as $v)
                {
                    $conf = json_decode($v['setting'] , true );
                    if(!empty($need_reload))
                    {
                        // 更新api缓存配置
                        if(!empty($conf[$this->yx_key]))
                        {
                            $api_setting_cache[$v['key'].$this->yx_key] = ['api'=>$v['key'],'status'=>$v['status']] ;
                        }
                        if(!empty($conf[$this->hy_key]))
                        {
                            $api_setting_cache[$v['key'].$this->hy_key] = ['api'=>$v['key'],'status'=>$v['status']];
                        }
                    }
                    //检测当前可用账号列表是否有余额不足的账号，并且有余额的账号更新进去redis
                    if($v['status'] == 1)
                    {
                        //营销账号
                        $key = "{$v['key']}&{$this->yx_key}";
                        if(empty($this->sms_api_arr[$key]))
                        {
                            $this->sms_api_arr[$key] = new Sms($v['key'], $conf[$this->yx_key]) ;
                        }
                        #查询余额
                        $balance_data = $this->sms_api_arr[$key]->balanceQuery();
                        #echo $key;print_r($balance_data);
                        if($balance_data)
                        {
                            // 提醒发送余额不足 ；
                            $this->notice($balance_data['num'], ['current_num'=>$balance_data['num'],'channel'=>$this->yx_key,'api'=>$v['key'],'account'=>$conf[$this->yx_key]['account']],$notice_setting['setting']);
                            if($balance_data['num']>0)
                            {
                                $this->redis_client->hset(MOBILE_CONF_TYPE,$key,json_encode($conf[$this->yx_key],JSON_UNESCAPED_UNICODE));
                            }
                            else
                            {
                                $this->redis_client->hdel(MOBILE_CONF_TYPE,$key);
                            }
                        }

                        //营销账号发送结果查询
                        $status_data = $this->sms_api_arr[$key]->getSendStatus();
                        if($status_data)
                        {
                            foreach ($status_data as $m=>$n)
                            {
                                try{
                                    $this->model['mobile_yingxiao_list']->where("msg_id = :id")->bind(['id'=>$n['msgid']])->update([
                                        'status'=>$n['status']?2:1,
                                        'status_info'=>"状态码:{$n['status']},信息:{$n['desc']},运营商回馈码:[{$n['code']}]",
                                        'accept_time'=>time(),
                                    ]);
                                }
                                catch (Exception $e)
                                {
                                    $error_string = sprintf("error:%s,code:%s,method：%s,line:%d,file stat:%s,trace:%s,",$e->getMessage(),$e->getCode(),__METHOD__,$e->getLine(),$e->getFile(),$e->getTraceAsString());
                                    $this->fileLog($error_string);
                                }
                            }
                        }
                        //行业账号
                        $key = "{$v['key']}&{$this->hy_key}";
                        if(empty($this->sms_api_arr[$key]))
                        {
                            $this->sms_api_arr[$key] = new Sms($v['key'], $conf[$this->hy_key]) ;
                        }
                        $balance_data   = $this->sms_api_arr[$key]->balanceQuery();
                        #echo $key;print_r($balance_data);
                        if($balance_data)
                        {
                            //todo:: 提醒发送余额不足 ；
                            $this->notice($balance_data['num'], ['current_num'=>$balance_data['num'],'channel'=>$this->hy_key,'api'=>$v['key'],'account'=>$conf[$this->hy_key]['account']],$notice_setting['setting']);
                            if($balance_data['num']>0)
                            {
                                $this->redis_client->hset(MOBILE_CONF_TYPE,$key,json_encode($conf[$this->hy_key],JSON_UNESCAPED_UNICODE));
                            }
                            else
                            {
                                $this->redis_client->hdel(MOBILE_CONF_TYPE,$key);
                            }
                        }

                        // 行业账号发送结果查询
                        $status_data = $this->sms_api_arr[$key]->getSendStatus();
                        if($status_data)
                        {
                            foreach ($status_data as $m=>$n)
                            {
                                try{
                                    $this->model['mobile_hangye_list']->where("msg_id = :id")->bind(['id'=>$n['msgid']])->update([
                                        'status'=>$n['status']?2:1,
                                        'status_info'=>"状态码:{$n['status']},信息:{$n['desc']},运营商回馈码:[{$n['code']}]",
                                        'accept_time'=>time(),
                                    ]);
                                }
                                catch (Exception $e)
                                {
                                    $error_string = sprintf("error:%s,code:%s,method：%s,line:%d,file stat:%s,trace:%s,",$e->getMessage(),$e->getCode(),__METHOD__,$e->getLine(),$e->getFile(),$e->getTraceAsString());
                                    $this->fileLog($error_string);
                                }
                            }
                        }
                    }
                }
                if(!empty($need_reload))
                {
                    $this->redis_client->set(MOBILE_API_SETTING_CACHE,json_encode($api_setting_cache,JSON_UNESCAPED_UNICODE));
                }
                unset($need_reload,$v,$m,$n,$res,$conf,$balance_data,$key,$api_setting_cache,$notice_setting);
            }
            else
            {
                $this->fileLog('更新配置进程在查询数据库的时候,没有查询到已设定的短信发送api和账号信息,方法：'.__METHOD__.',行号：'.__LINE__.',sql:'.Db::name('setting')->getLastSql());
            }
        }catch (Exception $e)
        {
            $error_string = sprintf("error:%s,code:%s,method：%s,line:%d,file stat:%s,trace:%s,",$e->getMessage(),$e->getCode(),__METHOD__,$e->getLine(),$e->getFile(),$e->getTraceAsString());
            $this->fileLog($error_string);
        }
        sleep(30);
    }

    /**
     * 发送短信
     * @param $api_obj_arr
     * @param $data
     * @return array
     */
    protected function send(&$api_obj_arr,$data)
    {
        if($data['appoint_api'])
        {
            if(empty($api_obj_arr[$data['channel']][$data['appoint_api']]))
            {
                $return = [
                    'status_info'=>'指定接口账号当前不可用(强制指定的发送api没有可用的账号，可能是账号错误或者欠费)',
                    'status'=>2,
                    'by_account'=>$this->api_list[$data['channel']][$data['appoint_api']],
                    'send_time'=>time(),
                    'msgid'=>'',
                ];
                goto end ;
            }
            $obj = $api_obj_arr[$data['channel']][$data['appoint_api']] ;
            $use_account = $this->api_list[$data['channel']][$data['appoint_api']];
            $api_ = $data['appoint_api'];
        }
        else
        {
            if(!empty($api_obj_arr[$data['channel']][$this->default_api_use]))// 默认账号发送，
            {
                $api_ = $this->default_api_use;
            }
            else//选取当前账号进行发送
            {
                $api_ = key($api_obj_arr[$data['channel']]);
            }
            if(!$api_)
            {
                $return = [
                    'status_info'=>'没有可用的短信发送接口(可能是配置中的所有账号欠费或者密码账号错误)',
                    'status'=>2,
                    'by_account'=>$this->api_list[$data['channel']][$data['appoint_api']],
                    'send_time'=>time(),
                    'msgid'=>'',
                ];
                goto end ;
            }
            $obj = current($api_obj_arr[$data['channel']]);
            $use_account = $this->api_list[$data['channel']][$api_];
        }
        if($this->debug)
        {
            $send_res = array('error'=>'505','info'=>"debug模式不会真实发送，只模拟返回结果",'msgid'=>'000');
        }
        else
        {
            $send_res = $obj->send($data['to'],$data['content'],$data['sign']);
        }
        $return = [
            'status_info'=>"状态码:{$send_res['error']},信息:{$send_res['info']}",
            'status'=>$send_res['error']?2:1,
            'by_account'=>$use_account,
            'msgid'=>(string)$send_res['msgid'],
            'send_time'=>time(),
        ];
        if($obj->isArrears())
        {
            unset($api_obj_arr[$data['channel']][$api_]);
            //todo :: 发送通知告知不可用
        }
        end :
        return $return ;
    }

    /**
     * 初始化基础设施
     * @param $method
     * @param $line
     * @param bool $need_init_api_obj
     * @return array|bool
     * @throws Exception
     */
    protected function baseInit($method , $line,$need_init_api_obj=true)
    {
        //初始化
        if(!$this->redis_client)
        {
            $this->redis_client = new RedisClient($this->redis_conf);
        }
        $tmp = $this->redis_client->HGETALL(MOBILE_CONF_TYPE);
        if(!$tmp)// 取不到配置不执行;
        {
            $this->fileLog('短信数据库任务进程:没有获取到redis存储的配置信息!,redis_error:'.$this->redis_client->getLastError().",行数：{$line},方法：{$method}");
            $return = false ;
            goto end ;
        }
        if($need_init_api_obj)
        {
            $api_obj_arr =[] ;
            foreach($tmp as $k=>$v)
            {
                $v = json_decode($v,true);
                $k_arr = explode('&', $k);
                if(!empty($this->sms_api_arr[$k_arr[1]][$k_arr[0]]))
                {
                    $api_obj_arr[$k_arr[1]][$k_arr[0]] = $this->sms_api_arr[$k_arr[1]][$k_arr[0]] ;
                }
                else
                {
                    $this->sms_api_arr[$k_arr[1]][$k_arr[0]] = new Sms($k_arr[0], $v) ;
                    $api_obj_arr[$k_arr[1]][$k_arr[0]] = $this->sms_api_arr[$k_arr[1]][$k_arr[0]] ;
                }
                $v['api'] = $k_arr[0];
                $this->api_list[$k_arr[1]][$k_arr[0]] = json_encode($v,true);
            }
            $return = $api_obj_arr;
        }
        else
        {
            $return = true ;
        }
        end:
        return $return ;
    }

    /**
     * 余额不足邮件提醒
     * @param $num
     * @param $info
     * @param bool $setting
     */
    protected function notice($num,$info,$setting = false )
    {
        try{
            if(!$setting)
            {
                $setting = $this->redis_client->hGet(SYSTEM_SETTING,MOBILE_ACCOUNT_NOT_ENOUGH_NOTICE);
            }
            $setting = json_decode($setting,true);
            if($setting)
            {
                if(empty($this->model['email_list']))
                {
                    $this->model['email_list'] = Db::name('email_list');
                }
                if($num <=$setting['notice_num'])
                {
                    $time_int = $this->redis_client->get("{$info['api']}&{$info['channel']}_notice_time");
                    if(!$time_int)// 20 分钟提醒一次
                    {
                        $this->redis_client->setex("{$info['api']}&{$info['channel']}_notice_time",$setting['notice_space']*60,time());
                        try{
                            $this->redis_client->Push(EMAIL_QUEUE, json_encode([
                                "api_time"       => time(),
                                "request_client" => "系统",
                                "template"       => "1",
                                "sign"           => "系统通知",
                                "to"             => join(',',$setting['send']),
                                "var_title"      => "",
                                "var_content"    => [$info['api'],$info['channel'],$info['account'],$info['current_num'],date('Y-m-d H:i:s')],
                                "add_time"       => time(),
                            ], JSON_UNESCAPED_UNICODE));
                        }
                        catch (Exception $e)
                        {
                            $error_string = sprintf("error:%s,code:%s,method：%s,line:%d,file stat:%s,trace:%s,",$e->getMessage(),$e->getCode(),__METHOD__,$e->getLine(),$e->getFile(),$e->getTraceAsString());
                            $this->fileLog($error_string);
                        }
                    }
                }
            }
        }
        catch(Exception $e)
        {
            $error_string = sprintf("error:%s,code:%s,method：%s,line:%d,file stat:%s,trace:%s,",$e->getMessage(),$e->getCode(),__METHOD__,$e->getLine(),$e->getFile(),$e->getTraceAsString());
            $this->fileLog($error_string);
        }
    }

    /**
     * 废弃 ，勿删
     * @param $setting
     * @param $val
     * @return int
     */
    protected function noticeTime($setting,$val)
    {
        $times = 0 ;
        $key_array = array_keys($setting);
        foreach ($setting as $k=>$v)
        {
            $line_bottom = next($key_array);
            if($val <=$k )
            {
                if($line_bottom!==false)
                {
                    if( $val >$line_bottom)
                    {
                        $times = $v ;
                        break ;
                    }
                }
                else
                {
                    $times = $v ;
                    break;
                }
            }
        }
        return $times ;
    }

    /**
     * 记录运行错误日志
     * @param $error_string
     */
    public function fileLog($error_string)
    {
        $error_file = dirname(dirname(dirname(__DIR__))).'/runtime/mobile/log/error.log';
        if(!is_dir(dirname($error_file)))
        {
            mkdir(dirname($error_file),0777,true);
        }
        file_put_contents($error_file, $error_string.' ['.date('Y-m-d H:i:s').']'.PHP_EOL,FILE_APPEND|LOCK_EX);
        if(stripos($error_file,'Connection timed out')!==false)
        {
            exit ;
        }
    }
}